<template>
  <div class="registe" style="overflow:hidden;">
    <div class="closeIcon" @click="goBack"><el-icon class="el-icon-close self-icon"></el-icon></div>
    <div class="registe-box">
      <div class="top">
        分店注册
      </div>
      <div class="mid">
        <el-form :model="dataForm"
                 :rules="dataRule"
                 ref="dataForm"
                 @keyup.enter.native="dataFormSubmit()"
                 status-icon
                 label-position="right"
                 label-width= '80px'
                 size="small"
                 :inline-message='true'
                 :hide-required-asterisk='true'>
          <el-form-item prop="shopOwner" label="店主姓名:" label-width="125px">
            <el-input class="info"
                      v-model="dataForm.shopOwner"
                      placeholder="店主名"></el-input>
          </el-form-item>
          <el-form-item prop="shopName" label="店铺名:" label-width="125px">
            <el-input class="info"
                      v-model="dataForm.shopName"
                      placeholder="店铺名"></el-input>
          </el-form-item>
          <el-form-item prop="mobile" label="手机号:" label-width="125px">
            <el-input class="info"
                      v-model="dataForm.mobile"
                      placeholder="手机号">
              <span slot="append" style="border:0;color:#1F87E8;background-color:rgba(0,0,0,0);width:100%;height:100%;" v-if="!isPending" @click="getCheckCode">获取验证码</span>
              <span slot="append" style="border:0;color:#606266;background-color:rgba(0,0,0,0);width:100%;height:100%;" v-if="isPending">重新发送（{{remainingTime}}）</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="checkCode" label="验证码:" label-width="125px">
            <el-input class="info"
                      v-model="dataForm.checkCode"
                      @change="checkMobile"
                      placeholder="验证码">
            </el-input>
          </el-form-item>
          <el-form-item prop="address" label="地址" label-width="125px">
            <v-distpicker @selected="addrSelect" @province='province' @city='city' @area='area' :province="dataForm.province" :city="dataForm.city" :area="dataForm.area" :placeholders="placeholders"></v-distpicker>
          </el-form-item>
          <el-form-item prop="shopAddress" label="详细地址:" label-width="125px">
            <el-input v-model="dataForm.shopAddress" style="margin-top:4px" class="info" placeholder='请将详细地址补充完整，无需再次填写省市区'></el-input>
          </el-form-item>
          <el-form-item prop="idCard" label="身份证正反面:" label-width="125px" :hide-required-asterisk='true'>
            <div style="display:flex;">
              <idUpload v-model="dataForm.id1" url ="/admin/file/upload/elementOpen" imgUrl ="https://xiaoxiangai.oss-cn-beijing.aliyuncs.com/2024/09/02/A14460.png"></idUpload>
              <idUpload v-model="dataForm.id2" url ="/admin/file/upload/elementOpen" imgUrl ="https://xiaoxiangai.oss-cn-beijing.aliyuncs.com/2024/09/02/A14460.png"></idUpload>

            </div>
          </el-form-item>
          <el-form-item label="营业执照:" label-width="125px" prop="bussinessLicense">
            <LisenceUpload   v-model="dataForm.bussinessLicense" url ="/admin/file/upload/elementOpen"></LisenceUpload  >
          </el-form-item>
          <el-form-item label="卫生许可证:" label-width="125px" prop="hygienicLicense">
            <LisenceUpload   v-model="dataForm.hygienicLicense" url ="/admin/file/upload/elementOpen"></LisenceUpload >
            <span style="font-size:12px;color:#B1B1B1;display:block;">卫生许可证/食品药品生产许可证  请选择任意一个证件上传</span>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="dataForm.checked"><span style="clolor:#606266;">我已阅读并同意</span></el-checkbox><span v-on:click.stop="openAggrement" style="color:#02A1E9;cursor: pointer;">《商家注册协议》</span>

          </el-form-item>
          <el-form-item>
            <span class="item-btn"><input type="button"
                     value="注册分店"
                     @click="dataFormSubmit()" style="width:90px"></span>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <aggrement v-if="aggrementVisible" ref="aggrement"></aggrement>
    <!-- <div class="bottom">Copyright © 2020 POS收银系统线上服务平台</div> -->
  </div>
</template>

<script>
import { clearLoginInfo } from '@/utils'
import { isMobile,isIDCard } from '@/utils/validate'
import myMap from './map'
import BaiduMap from '../../utils/map'
import idUpload from '@/components/id-registe'
import LisenceUpload from '@/components/lisence-registe'
import VDistpicker from 'v-distpicker'
import aggrement from './aggrement.vue'

export default {
  data () {
    var validateMobile = (rule,value,callback) =>{
      if (!isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else{
        callback()
      }
    }

    var validatecheckCode = (rule, value, callback) => {
      if (this.checkCodeIsRunning) {
        return
      }
      this.checkCodeIsRunning = true
      if (this.codeIsLegal == this.dataForm.checkCode) {
        callback()
      }else if(this.codeIsLegal == 'none'){
        callback(new Error('验证码失效，请重新验证'))
      } else{
        this.$http({
          url: this.$http.adornUrl('/p/sms/validate'),
          method: 'get',
          params: this.$http.adornParams({
            mobile: this.dataForm.mobile,
            code: this.dataForm.checkCode
          })
        }).then(({data}) =>{
          if (data == '000') {
            callback(new Error('检验次数次数过多，请稍后重试'))
          }else if (data == '111') {
            callback(new Error('验证码错误'))
          }else if (data == '222') {
            callback(new Error('验证码已过期'))
          }else if (data == '999'){
            this.codeIsLegal = this.dataForm.checkCode
            setTimeout(() =>{
              this.codeIsLegal = 'none'
            },10*60*1000)
            callback()
          }
        })
      }
      this.checkCodeIsRunning = false
    };
    var validateAddress = (rule, value, callback) => {
      console.log('running');
      console.log(this.dataForm);
      if (!this.dataForm.province || this.dataForm.province == '省') {
        callback(new Error('请选择省份'))
      }else if (!this.dataForm.city || this.dataForm.city == '市') {
        callback(new Error('请选择市'))
      }else if (!this.dataForm.area || this.dataForm.area == '区') {
        callback(new Error('请选择区域'))
      }else{
        callback()
      }

    };
    var validateIdCard = (rule,value,callback) =>{
      if (!this.dataForm.id1 || !this.dataForm.id2) {
        callback(new Error("请上传身份证正反面两面"))
      } else {
        callback()
      }
    }
    var validateBussinessLicense = (rule,value,callback) =>{
      if (!this.dataForm.bussinessLicense) {
        callback(new Error("请上传营业执照"))
      } else{
        callback()
      }
    }
    var validatehygienicLicense = (rule,value,callback) =>{
      if (!this.dataForm.hygienicLicense) {
        callback(new Error("请上传卫生许可证"))
      } else{
        callback()
      }
    }
    return {
      aggrementVisible: false,
      mobileIslegal: false,
      codeIsLegal: false,
      checkCodeIsRunning :false,
      dataForm: {
        userName: '',
        password: '',
        confirmPassword:'',
        shopOwner: '',
        shopName: '',
        mobile: '',
        bussinessLicense: '',
        hygienicLicense: '',
        foodBusinessLicense: '',
        province: '湖北省',
        city: '襄阳市',
        area: '樊城区',
        shopAddress: '',
        checked: true,
      },
      placeholders: {},
      remainingTime: 60,
      isPending: false,
      coordinate:{},
      addressArray:{},
      dataRule: {
        shopName: [
          { required: true, message: '店铺名不能为空', trigger: 'blur' }
        ],
        shopOwner: [
          { required: true, message: '请输入店主名', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger:'blur'}
        ],
        checkCode: [
          { required: true, message: '请填写验证码', trigger: 'blur' },
          { validator: validatecheckCode, trigger:'blur'}
        ],
        address: [
          { validator: validateAddress, trigger:'blur' }
        ],
        idCard: [
          { validator: validateIdCard, trigger:'blur'}
        ],
        shopAddress: [
          { required: true, message: '请填写详细地址，精确到门牌号', trigger: 'blur' },
        ],
        bussinessLicense: [
          { required: true, message: '请上传营业执照',trigger: 'blur' },
          { validator: validateBussinessLicense, trigger:'blur' },
        ],
        hygienicLicense: [
          { required: true, message: '请上传卫生许可证或食品药品生产许可证',trigger: 'blur' },
          { validator: validatehygienicLicense, trigger:'blur' },
        ],
      },
    }
  },

  computed:{
    address(){
      return this.province + this.city + this.area
    },
    idCard(){
      return this.dataForm.id1+','+this.dataForm.id2
    },
    mainStore(){
      return this.$store.state.user.shopId
      // get (){  },
    },
  },

  watch:{
  },


  components:{
    VDistpicker,
    idUpload,
    LisenceUpload ,
    aggrement
  },


  created(){
  },

  mounted() {
    window.jsonpCallback = (data) => {
        console.log(data)
    }
  },

  methods: {
    logout(){
      this.$http({
          url: this.$http.adornUrl('/sys/logout'),
          method: 'post',
          data: this.$http.adornData()
      }).then((res) =>{
          console.log(res)
          clearLoginInfo()
          this.$router.push({name:"login"})
      }).catch((err) =>console.log(err))
    },


    // 提交表单
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/shop/shopDetail/openBranch'),
            method: 'post',
            data:{
              mainStore: this.mainStore,
              shopOwner: this.dataForm.shopOwner,
              shopName: this.dataForm.shopName,
              mobile: this.dataForm.mobile,
              province: this.dataForm.province,
              city: this.dataForm.city,
              area: this.dataForm.area,
              shopAddress: this.dataForm.shopAddress,
              shopLng: this.coordinate.lng,
              shopLat: this.coordinate.lat,
              idCard: this.dataForm.id1+','+this.dataForm.id2,
              bussinessLicense: this.dataForm.bussinessLicense,
              hygienicLicense: this.dataForm.hygienicLicense,
            }
          }).then(({data}) => {
            if (data == 'success') {
              this.$message({
                message: '注册成功，请等待管理员审核通过后登录使用',
                type: 'success'
              });
            this.$router.push('/home')
            }else{
              this.$message.error('注册失败，请重试或联系平台供应方');

            }
          }).catch(() => {
          })
        }else{
          this.$message.error('信息填写不完整或填写错误，请检查您填写的信息')
        }
      })
    },

    uploadFile(e){
      console.log(e);
    },


    checkMobile(){
      console.log(this.dataForm.mobile)

    },

    getCheckCode(){
      if (!this.dataForm.mobile) {
        this.$message.error('请先输入手机号')
        return
      }
      if (!isMobile(this.dataForm.mobile)) {
        this.$message.error('手机号格式错误')
        return
      }
      this.sendMsg()
      this.isPending = true
      var conter = setInterval(() => {
        this.remainingTime-=1
      }, 1000);
      setTimeout(() =>{
        clearInterval(conter)
        this.isPending = false
        this.remainingTime = 60
      },60000)
    },

    sendMsg(){
      console.log('running');
      this.$http({
        url: this.$http.adornUrl('/p/sms/send'),
        method: 'get',
        params: this.$http.adornParams({
          mobile: this.dataForm.mobile
        })
      }).then((res) =>{
          console.log(res);
      })
    },

    addrSelect(data){
      this.dataForm.province = data.province.value
      this.dataForm.city = data.city.value
      this.dataForm.area = data.area.value
      this.$refs.dataForm.validateField('address');
    },

    province(data){
      this.$refs.dataForm.validateField('address');
    },
    city(data){
      this.$refs.dataForm.validateField('address');
    },
    area(data){
      this.$refs.dataForm.validateField('address');
    },
    openAggrement(){
      this.aggrementVisible = true
      this.$nextTick(() =>{
        this.$refs.aggrement.init()
      })
    },

    goBack(){
      console.log("running");
      history.go(-1)
    }


  },

}
</script>

<style scoped>
.registe {
  width: 100%;
  height: 100%;
  background-size: cover;
}
.registe .registe-box {
  width: 100%;
  margin-bottom: 100px;
  margin-top: 20px;
}
.registe .registe-box .top {
  margin-bottom: 30px;
  font-size: 22px;
  margin-left: 20px;
}
.registe .registe-box .top::before {
  content: '';
  border-right: 3px;
  border-left: 3px solid #0087EB;
  margin-right: 6px;
}
.registe .registe-box .mid {
  font-size: 14px;
  margin-left: 46%;
  transform: translateX(-50%);
}
.registe .registe-box .mid .item-btn {
  margin-top: 20px;
}
.registe .registe-box .mid .item-btn input {
  border: 0;
  width: 100%;
  height: 40px;
  box-shadow: 0;
  background: #1f87e8;
  color: #fff;
  border-radius: 3px;
}
/* .open {
  width: 410px;
} */
.registe-captcha {
  height: 40px;
}
.registe .registe-box>>> .bottom {
  width: 100%;
  color: #999;
  font-size: 12px;
  text-align: center;
  margin-bottom: 20px;
}


.registe .registe-box>>> .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.registe .registe-box>>> .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.registe .registe-box>>> .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.registe .registe-box>>> .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.registe .registe-box>>> .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
  width: 680px;
}
.registe .registe-box>>> .distpicker-address-wrapper select{
  width: 134px;
  font-size: 14px;
  height: 36px;
  line-height: 36px;
  color: #606266;
}
.registe .registe-box>>> .el-checkbox{
  margin-right: 0;
}
.registe .registe-box>>> label.el-form-item__label::before {
  content: '*';
  color: #F56C71;
  margin-right: 3px;
  height: 15px;
}
.closeIcon{
  position: absolute;
  right: 30px;
  top: 30px;
  font-size: 30px;
  z-index: 1000;
}

</style>
